const md5 = require("md5");
const adminDao = require("../dao/operation/adminDao")
const jwt = require("../utils/jwt")
const { ValidationError } = require("../utils/error")

// admin模块的业务逻辑层面

/**
 * 
 * @param {*} res 响应
 * @param {*} loginInfo 用户信息
 */
module.exports.loginService = async function(res, loginInfo) {
    loginInfo.loginPwd = md5(loginInfo.loginPwd)
    let time = 1

    // 数据验证
    const result = await adminDao.login(loginInfo)
    if (result && result.dataValues) {
        if (loginInfo.remember) {
            time = loginInfo.remember - 0
        }
        const info = {
                id: result.id,
                loginId: result.loginId,
                name: result.name
            }
            // 添加token
        const token = jwt.award(res, info,
            time * 24 * 3600
        )
        return info
    } else {
        return new ValidationError("用户名或密码错误").toResponseJSONError()
    }
}

module.exports.updateAdminService = async function(res, info) {
    const result = await adminDao.login({
        loginId: info.loginId,
        loginPwd: md5(info.oldLoginPwd)
    })
    if (result && result.dataValues) {
        // 有此用户,修改
        const newInfo = {
            loginId: info.loginId,
            loginPwd: md5(info.loginPwd),
            name: info.name
        }
        await adminDao.updateAdmin(newInfo)

        return {
            loginId: info.loginId,
            id: result.dataValues.id,
            name: info.name
        }
    } else {
        return new ValidationError("验证失败，用户名或密码错误").toResponseJSONError()
    }
}